<template>
  <div class="page_table_wrapper">
    <el-table
      ref="table"
      :data="tableData"
      :border="border"
      :stripe="stripe"
      :height="tableMaxHeight"
      header-cell-class-name="headername"
      cell-class-name="rowname"
      v-loading="loading"
      :span-method="objectSpanMethod"
      @selection-change="handleSelectionChange"
      @row-dblclick="handleRowDBClick"
      @sort-change="handleSortChange"
      :row-class-name="rowClassName"
      style="width: 100%"
      element-loading-text="拼命加载数据中"
      element-loading-spinner="el-icon-loading"
    >
      <el-table-column
        v-if="showSelect"
        type="selection"
        align="center"
        header-align="center"
        width="55"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        v-if="showIndex"
        type="index"
        align="center"
        header-align="center"
        label="序号"
        width="80"
        show-overflow-tooltip
      ></el-table-column>
      <slot></slot>
      <div style="padding-top: 10px" slot="empty" v-if="data&&data.length==0&& !isOverTime">
        <img src="./empty.png" ref="img" alt="暂无数据" />
        <p >暂无数据</p>
      </div>
      <div slot="empty" v-else>
        <img src="./overtime.png" alt="服务器未响应，请检查网络是否连接" />
        <p >服务器未响应，请检查网络是否连接</p>
      </div>
    </el-table>
    <el-pagination
      ref="pagination"
      class="pagination"
      background
      v-if="showPagination"
      @current-change="handleCurrentChange"
       @size-change="handleSizeChange"
      :current-page="page"
      :page-size="pageSize"
      :page-count="pageNum"
      :pager-count="pagerCount"
      :layout="layout"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: 'noKeepalive',
  data() {
    return {
      tableMaxHeight: 0,
      tipText: '暂无数据',
      spanArr: [], // 二维数组，用于存放单元格合并规则
      position: 0, // 用于存储相同项的开始index
      tableData: []
    }
  },
  props: {
    autoHeightFlag: {
      type: Boolean,
      default: true
    },
    winH: {
      type: Number
    },
    layout: {
      type: String,
      default: 'total, prev, pager, next, sizes, jumper'
    },
    page: {
      type: Number,
      default: 0
    },
    pageSize: {
      type: Number,
      default: 10
    },
    total: {
      type: Number,
      default: 0
    },
    pageNum: {
      type: Number,
      default: 10
    },
    pagerCount: {
      type: Number,
      default: 7
    },
    border: {
      type: Boolean,
      default: false
    },
    stripe: {
      type: Boolean,
      default: false
    },
    showSelect: {
      // 是否显示勾选框
      type: Boolean,
      default: false
    },
    showIndex: {
      // 是否显示序号
      type: Boolean,
      default: false
    },
    data: {
      type: Array,
      default() {
        return []
      }
    },
    editHeight: {
      // 调整高度
      type: Number
    },
    loading: {
      type: Boolean,
      default: false
    },
    // 判断后端是否请求超时或者接口损坏
    isOverTime: {
      type: Boolean,
      default: false
    },
    // 是否显示分页
    showPagination: {
      type: Boolean,
      default: true
    },
    // 合并表格参数
    spanMetnodsOption: {
      type: Array,
      default: () => {
        return [
          // {
          //   index: 1, // 列索引
          //   prop: 'name' // 需要合并的数据字段名
          // }
        ]
      }
    },
    rowClassName: {
      type: Function
    }
  },
  activated() {
    this.maxHeightUpdate()
  },
  mounted() {
    if (this.autoHeightFlag) {
      window.addEventListener('resize', this.maxHeightUpdate)
    }
    this.maxHeightUpdate()
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler() {
        if (this.spanMetnodsOption.length) {
          this.rowspan()
          this.tableData = []
          setTimeout(() => {
            this.tableData = this.data
          }, 100)
        } else {
          this.tableData = this.data
        }
      }
    }
  },
  methods: {
    // 当前页码变化
    handleCurrentChange(page) {
      this.$emit('currentChange', page)
    },
    handleSizeChange(size) {
      this.$emit('sizeChange', size)
    },
    // 更新表格高度  使页面能同时看到表格和页码
    maxHeightUpdate() {
      this.$nextTick(() => {
        setTimeout(() => {
          // 如果有设置最大高度则使用 否则自己重新计算
          const editHeight = this.editHeight || 0
          const winH = this.winH || window.innerHeight
          const tableTop = this.$refs.table.$el.getBoundingClientRect().top
          if (!this.autoHeightFlag) {
            this.tableMaxHeight = editHeight || 400
          } else {
            this.tableMaxHeight = Math.max(winH - tableTop - (16 + 36 + 24 + 20), editHeight)
            // 总高度 - 表格顶部高度 - 表格下方必须高度
          }
        }, 20)
      })
    },
    // 表格多选
    handleSelectionChange(val) {
      this.$emit('selection-change', val)
    },
    // 某行双击时
    handleRowDBClick(row, column, event) {
      this.$emit('row-dblclick', row, column, event)
    },
    // 当表格的排序条件发生变化的时候会触发该事件
    handleSortChange({ column, prop, order }) {
      this.$emit('sortChange', { column, prop, order })
    },
    rowspan() {
      this.spanArr = []
      this.spanMetnodsOption.forEach(({ index, prop }) => {
        if (typeof (index) !== 'number' || !prop) {
          throw Error('必须传入列索引index，和需要用作当列合并的数据字段名')
        }
        this.spanArr[index] = []
        this.position = 0
        this.data.forEach((item, idx) => {
          if (idx === 0) {
            this.spanArr[index].push(1)
            this.position = 0
          } else {
            if (this.data[idx][prop] === this.data[idx - 1][prop]) {
              this.spanArr[index][this.position] += 1// 有相同项
              this.spanArr[index].push(0) // 名称相同后往数组里面加一项0
            } else {
              this.spanArr[index].push(1)// 同列的前后两行单元格不相同
              this.position = idx
            }
          }
        })
      })
    },
    // 表格单元格合并
    // eslint-disable-next-line no-unused-vars
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const _row = this.spanArr[columnIndex] ? this.spanArr[columnIndex][rowIndex] : 1
      const _col = _row > 0 ? 1 : 0
      // console.log('第' + rowIndex + '行', '第' + columnIndex + '列', 'rowspan:' + _row, 'colspan:' + _col)
      return {
        rowspan: _row,
        colspan: _col
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.maxHeightUpdate)
  }
}
</script>

<style lang="scss">
.page_table_wrapper {
  .pagination {
    margin-top: 16px;
    text-align: right;
  }
  .cell {
    line-height: 25px;
    white-space: nowrap;
  }
}
</style>
